package raojt.day0109.lotteryProject.dao.impl;

import raojt.day0109.lotteryProject.dao.LotteryBusinessDao;
import raojt.day0109.lotteryProject.entity.User;
import raojt.day0109.lotteryProject.uilts.BaseDao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class LotteryBusinessDaoImpl extends BaseDao implements LotteryBusinessDao {
    @Override
    public List<User> selectAll(Map<String, Object> map) {
        List<User> userLists = new ArrayList<>();
        User user = null;
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT ID,USER_NAME,MARK_NO,STATUS,PHONE,OPEN_DATE FROM T_USER ");
        sql.append(" WHERE 1 = 1 ");
        Object markNo = map.get("userMarkNo");
        Object status = map.get("userStatus");
        if ((!"".equals(markNo) & markNo != null) & status == null) {
            sql.append(" AND MARK_NO LIKE ? ");
            sql.append(" ORDER BY ID ");
            markNo = "%" + markNo + "%";
            rs = super.exectuteQuery(sql.toString(), new Object[]{markNo});
        } else if ((!"".equals(status) & status != null) & markNo == null) {
            sql.append(" ORDER BY ID ");
            sql.append(" AND STATUS = ? ");
            rs = super.exectuteQuery(sql.toString(), new Object[]{status});
        } else {
            sql.append(" ORDER BY ID ");
            rs = super.exectuteQuery(sql.toString());
        }

        try {
            while (rs.next()) {
                user = new User();
                user.setId(rs.getString("ID"));
                user.setUserName(rs.getString("USER_NAME"));
                user.setMarkNo(rs.getString("MARK_NO"));
                user.setStatus(rs.getString("STATUS"));
                user.setPhone(rs.getString("PHONE"));
                user.setOpenDate(rs.getDate("OPEN_DATE"));
                userLists.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            super.closeAll(conn, pstmt, rs);
        }
        return userLists;
    }

    @Override
    public int addUser(User user) {
        int addRes = 0;
        String sql = "INSERT INTO T_USER(ID,USER_NAME,MARK_NO,STATUS,PHONE,OPEN_DATE)\n" +
                "VALUES(SEQ_T_USER_ID.NEXTVAL,?,?,1,?,SYSDATE)";
        addRes = super.executeUpdate(sql, new Object[]{user.getUserName(), user.getMarkNo(), user.getPhone()});
        return addRes;
    }

    @Override
    public int update(User user) {
        int updateRes = 0;
        String sql = "UPDATE T_USER SET STATUS = ? WHERE ID = ?";
        updateRes = super.executeUpdate(sql, new Object[]{user.getStatus(), user.getId()});
        return updateRes;
    }

    @Override
    public int deleteUser(User user) {
        String sql = " DELETE T_USER WHERE MARK_NO = ? ";
        int deleteRes = super.executeUpdate(sql, new Object[]{user.getMarkNo()});
        return deleteRes;
    }
}
